import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { AlertController, NavController } from "@ionic/angular";

@Component({
  selector: "app-reg",
  templateUrl: "./reg.page.html",
  styleUrls: ["./reg.page.scss"],
})
export class RegPage implements OnInit {
  constructor(
    public router: NavController,
    public http: HttpClient,
    public route: ActivatedRoute,
    public alertC: AlertController
  ) {}

  doReg(uname: HTMLInputElement, upwd: HTMLInputElement) {
    if (
      uname.value.length >= 2 &&
      uname.value.length <= 9 &&
      upwd.value.length >= 6 &&
      upwd.value.length <= 12
    ) {
      let url = "http://xiaoshuogebed.applinzi.com/reg";
      let body = `uname=${uname.value}&upwd=${upwd.value}`;
      const httpOptions = {
        headers: new HttpHeaders({
          "Content-Type": "application/x-www-form-urlencoded",
        }),
      };
      this.http.post(url, body, httpOptions).subscribe((res: Result) => {
        let code = res.code;
        if (code == 0) {
          this.alertC
            .create({
              header: "很遗憾，注册失败！",
              message: "用户名或密码格式错误",
              buttons: ["确定"],
            })
            .then((res) => res.present());
        } else {
          this.router.navigateForward("/login");
        }
      });
    } else {
      this.alertC
        .create({
          header: "提示",
          message: "用户名2~9位,密码6~12位！",
          buttons: ["确定"],
        })
        .then((res) => res.present());
    }
  }
  ngOnInit() {}
}
interface Result {
  code: number;
  msg: string;
}
